package cn.openea.perpartner.meily.web.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.openea.perpartner.common.core.exception.ServiceException;
import cn.openea.perpartner.common.core.web.domain.AjaxResult;
import cn.openea.perpartner.meily.web.entity.BuyingRecord;
import cn.openea.perpartner.meily.web.entity.Goods;
import cn.openea.perpartner.meily.web.entity.GroupBuyingSub;
import cn.openea.perpartner.meily.web.entity.dto.GroupDto;
import cn.openea.perpartner.meily.web.mapper.BuyingRecordMapper;
import cn.openea.perpartner.meily.web.service.IBuyingRecordService;
import cn.openea.perpartner.meily.web.service.IGoodsService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 *
 * (BuyingRecord)表服务实现类
 *
 * @author rains
 * @since 2023-02-09 17:20
 */
@Transactional
@Slf4j
@Service("buyingRecordService")
public class BuyingRecordServiceImpl extends ServiceImpl<BuyingRecordMapper, BuyingRecord> implements IBuyingRecordService {

    @Resource
    private IGoodsService goodsService;

    @Value("${payment.order.authSalt}")
    private String authSalt;
    @Value("${payment.order.getTokenUrl}")
    private String getOrderSysTokenUrl;
    @Value("${payment.order.addOrderUrl}")
    private String addOrderUrl;

    /**
     * 新增
     * @param buyingRecord 实体对象
     * @return 新增结果
     */
    @Override
    public boolean insert(BuyingRecord buyingRecord) {

        boolean flag = false;

        if(save(buyingRecord)){

            // 根据商品编号获取 分享报酬
            Goods goods = goodsService.getById(buyingRecord.getGoodsId());

            // 保存记录到订单系统
            JSONObject object = new JSONObject();
            object.put("orderId", buyingRecord.getOrderNo());// 订单编号（meily_group_buying_sub表中的order_id）
            object.put("orderName", "购买" + buyingRecord.getGoodsName());// 订单名称
            object.put("orderStatus", "已支付");// 订单状态。0:待支付；1:已支付；2:支付取消；(默认0)
            object.put("orderType", "购买商品");// 订单类型。0:购买商品
            object.put("orderPrice", buyingRecord.getPayAmount());// 订单金额
            object.put("orderImages", goods.getGoodsImages().split(",")[0]);// 订单图片
            object.put("orderLink", "/pages_private_scene2/GroupPurchase/OrderDetails?recordId="+buyingRecord.getGroupBuyingSubId());// 订单详情地址
            object.put("remark", "购买了" + buyingRecord.getBuyQuantity() + "件商品");// 订单备注
            object.put("sceneId", buyingRecord.getSceneId());// 场景id
            object.put("sourceId", buyingRecord.getId());// 来源id（meily_buying_record表中的唯一id）
            object.put("createUser", buyingRecord.getBuyerId());// 订单创建者id
            object.put("createUserName", buyingRecord.getBuyerName());// 订单创建者昵称
            object.put("createUserAvatar", buyingRecord.getBuyerAvatarUrl());// 订单创建者头像
            object.put("sourceModule", "meily_group_buying_sub");// 来源模块（数据表名）
            object.put("originalPayAmount", buyingRecord.getOriginalPayAmount());// 原来金额
            object.put("couponId", buyingRecord.getCouponId());// 优惠券id
            object.put("couponAmount", buyingRecord.getCouponAmount());// 优惠券金额
            object.put("useDeduction", buyingRecord.getUseDeduction());// 是否使用抵扣
            object.put("deductionAmount", buyingRecord.getDeductionAmount());// 抵扣金额
            object = getToken(object);
            JSONObject resObj = saveRecord2OrderSys(object);
            if (ObjectUtil.isNotEmpty(resObj) && "200".equals(resObj.getString("code"))) {
                flag = true;
            }
        }
        return flag;
    }

    /**
     * 分页查询
     * @param groupDto 实例对象
     * @return 查询结果
     */
    @Override
    public List<BuyingRecord> selectList(GroupDto groupDto) {
        LambdaQueryWrapper<BuyingRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(BuyingRecord::getCreateTime);
        return list(wrapper);
    }

    /**
     * 获取当前月（不含当天）所有购买记录
     * @return 查询结果
     */
    @Override
    public List<BuyingRecord> getCurrentMonthList() {
        return baseMapper.getCurrentMonthList();
    }

    @Override
    public String getGoodsSalesVolumeByGoodsNo(String goodsNo) {
        QueryWrapper<BuyingRecord> wrapper = new QueryWrapper<BuyingRecord>();
        wrapper.last(" and goods_no = '"+goodsNo+"' ");
        long soldNum = baseMapper.getGoodsSalesVolume(wrapper);
        return Convert.toStr(soldNum);
    }

    /** **************************** 2023-05-04 add by lys start *************************************** */

    /**
     * 获取商品总销量
     * 商品总销量 = 自定义销量 + 实际销量
     * @param groupDto 实体对象
     * @return 查询结果
     */
    @Override
    public long getTotalSales(GroupDto groupDto) {

        LambdaQueryWrapper<BuyingRecord> queryWrapper = new LambdaQueryWrapper<>();

        StringBuffer queryStr = new StringBuffer();

        // 商品id
        if(StrUtil.isNotBlank(groupDto.getGoodsId())){
            queryStr.append(" and goods_id = '"+groupDto.getGoodsId()+"'");
        }

        // 商品编号
        if(StrUtil.isNotBlank(groupDto.getGoodsNo())){
            queryStr.append(" and goods_no = '"+groupDto.getGoodsNo()+"'");
        }

        // 周期串
        if(StrUtil.isNotBlank(groupDto.getCycle())){
            queryStr.append(" and cycle = '"+groupDto.getCycle()+"'");
        }

        // 来源id(拼团主文档id或商品id)
        if(StrUtil.isNotBlank(groupDto.getSourceId())){
            queryStr.append(" and source_id = '"+groupDto.getSourceId()+"'");
        }

        queryWrapper.last(" "+ queryStr + " ");

        // 商品实际总销量
        long goodsTotalSales = baseMapper.getTotalSales(queryWrapper);

        // 获取自定义销量（商品信息中）
        Goods goods = new Goods();
        if(StrUtil.isNotBlank(groupDto.getGoodsId())){
            goods = goodsService.getById(groupDto.getGoodsId());
        }
        if(goods != null || BeanUtil.isNotEmpty(goods)){
            String customSales = goods.getCustomSales();// 自定义销量
            if(StrUtil.isNotBlank(customSales) && Long.parseLong(customSales) > 0){
                goodsTotalSales += Long.parseLong(customSales);
            }
        }
        return goodsTotalSales;
    }

    /**
     * 获取商品实际销售量
     * @param groupDto 实体对象
     * @return 查询结果
     */
    @Override
    public long getActualSales(GroupDto groupDto) {

        LambdaQueryWrapper<BuyingRecord> queryWrapper = new LambdaQueryWrapper<>();

        StringBuffer queryStr = new StringBuffer();

        // 商品id
        if(StrUtil.isNotBlank(groupDto.getGoodsId())){
            queryStr.append(" and goods_id = '"+groupDto.getGoodsId()+"'");
        }

        // 商品编号
        if(StrUtil.isNotBlank(groupDto.getGoodsNo())){
            queryStr.append(" and goods_no = '"+groupDto.getGoodsNo()+"'");
        }

        // 周期串
        if(StrUtil.isNotBlank(groupDto.getCycle())){
            queryStr.append(" and cycle = '"+groupDto.getCycle()+"'");
        }

        // 来源id(拼团主文档id或商品id)
        if(StrUtil.isNotBlank(groupDto.getSourceId())){
            queryStr.append(" and source_id = '"+groupDto.getSourceId()+"'");
        }

        queryWrapper.last(" "+ queryStr + " ");

        // 商品实际总销量
        return baseMapper.getTotalSales(queryWrapper);
    }

    /** **************************** 2023-05-04 add by lys end *************************************** */

    /**
     * 获取token与authstr
     *
     * @param
     * @return
     */
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public JSONObject getToken(JSONObject object) {
        HttpResponse resp = HttpRequest.post(getOrderSysTokenUrl)
                .header("Content-Type", "application/json")
                .header("Accept", "application/json")
                .body(object.toJSONString())
                .execute();
        try {
            JSONObject obj = JSON.parseObject(resp.body());
            String token = obj.getString("data");
            String tmpStr = authSalt.charAt(2) + authSalt.charAt(8) + token + authSalt.charAt(10) + authSalt.charAt(5);
            object.put("token", token);
            object.put("authStr", SecureUtil.md5(tmpStr));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return object;
    }

    /**
     * 保存记录到订单系统
     *
     * @return
     */
    public JSONObject saveRecord2OrderSys(JSONObject object) {
        JSONObject obj = new JSONObject();
        HttpResponse resp = HttpRequest.post(addOrderUrl)
                .header("Content-Type", "application/json")
                .header("Accept", "application/json")
                .body(object.toJSONString())
                .execute();
        try {
            obj = JSON.parseObject(resp.body());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }
}
